import Cookies from 'js-cookie'
import envhelper from '@nickfan/envhelper';
import { HttpMenuList, HttpModuleList } from "../service/base";
import { handleHostname } from '../utils/tools'

// 为防止初始化时localstorage和sessionstorage还未重写出现问题，用函数包裹，在storeInstance实例化时才运行
export default function layout() {
    return {

        namespaced: true,
        state: {
            navTitleIds: [],
            routeId: Cookies.get('ROUTEID') || '',
            menuList: JSON.parse(sessionStorage.MENULIST || "{}"),
            moduleList: JSON.parse(localStorage.MODULELIST || "{}"),
            sysScopeList: JSON.parse(localStorage.SYSSCOPELIST || "{}"),
            noticeEventTypes: JSON.parse(localStorage.NOTICEEVENTTYPES || "[]"),//通知类型
        },
        getters: {
            getMenuList(state) {
                const obj = {}, menuList = state.menuList;
                Object.keys(menuList).forEach(function (key) {
                    obj[key] = this[key];
                }, menuList);
                return obj;
            },
            getNavTitle(state, getters) {
                const { navTitleIds } = state,
                    menuList = getters.getMenuList,
                    data = [];
                // console.log(navTitleIds,'dddddd');
                navTitleIds.forEach(function (id) {
                    const item = menuList[id];
                    if (item) data.push(item);
                });
                return data;
            },
            getModuleMap(state, getters) {


                let nodes = getters.getMenuList;
                let nodeIdMap = [];
                let nodeParentIdMap = [];
                let nodeChildrenIdMap = [];
                let queue = [];
                let firstChildrenNodes = [];
                let newobj = {};
                for (let key in nodes) {
                    let node = nodes[key];
                    nodeParentIdMap[node.id] = node.parentId;//通过 nodeid 快速定位到 父id
                    //找第一层根节点,复制一份
                    let newNode = JSON.parse(JSON.stringify(node));
                    if (node.moduleId && node.depth == 2) {
                        firstChildrenNodes.push(newNode);
                    }
                    nodeIdMap[node.id] = newNode;//通过node id  快速定位到 node
                    if (!nodeChildrenIdMap[node.parentId]) {
                        nodeChildrenIdMap[node.parentId] = [];//通过 nodeid 快速 定位到 子节点数组
                    }
                    nodeChildrenIdMap[node.parentId].push(node.id);
                }
                firstChildrenNodes.map(node => {
                    let nodeChildrenIds = nodeChildrenIdMap[node.id];
                    queue = queue.concat(nodeChildrenIds)
                })


                while (queue.length > 0) {
                    let node = nodeIdMap[queue[0]];
                    if (node) {
                        let nodeChildrenIds = nodeChildrenIdMap[node.id];
                        // let nodeParentChildrenIds = nodeChildrenIdMap[node.parentId];
                        let nodeParentChildrenIds = nodeChildrenIdMap[nodeParentIdMap[node.id]];
                        if (node.menuType == 'NO') {
                            if (nodeParentChildrenIds && nodeParentChildrenIds.indexOf(node.id) > -1) {
                                nodeParentChildrenIds.splice(nodeParentChildrenIds.indexOf(node.id), 1)
                            }

                            //元素parentId改为更上一层parentId
                            if (nodeChildrenIds) {
                                queue = queue.concat(nodeChildrenIds)
                                nodeChildrenIds.map(id => {
                                    nodeParentIdMap[id] = node.parentId;
                                })
                            }
                        } else if (node.menuType == 'YES') {
                            if (nodeParentChildrenIds.indexOf(node.id) < 0) {
                                nodeParentChildrenIds.push(node.id)
                            }
                        }
                    }
                    queue.splice(0, 1);
                }
                firstChildrenNodes.map(node => {
                    node.linklistId = nodeChildrenIdMap[node.id]
                })
                Object.values(firstChildrenNodes).forEach(item => {
                    const { moduleId } = item;
                    if (item.depth == 1) return;
                    if (newobj[moduleId]) {
                        newobj[moduleId].push(item);
                    } else {
                        newobj[moduleId] = [item];
                    }
                });
                Object.keys(newobj).forEach(key => {
                    newobj[key].sort(function (pre, next) {
                        return pre.sortIndex - next.sortIndex
                    })
                });
                // console.log(newobj,'2222')

                // console.log(obj,'obobobobo')
                return newobj;
            },

            // 获取面包屑title list 数据
            getRouteTitleList(state, getters) {
                return function (path) {
                    const menuList = state.menuList,
                        list = [],
                        iterator = function (item) {
                            const { moduleId, parentId, props, labelId, title, linklistId, langKey } = item,
                                parent = menuList[parentId];
                            const data = linklistId ? { title, langKey } : { langKey, title, to: props.to, href: props.href };
                            if (parentId && labelId !== 'GLOBAL_ROOT') {
                                list.unshift(data);
                            }
                            if (!parent || moduleId && (moduleId != parent.moduleId)) return;
                            iterator(parent);
                        };
                    const routeData = getters.getMatchRoute(path, Object.values(menuList));
                    if (routeData) iterator(routeData);
                    // const last = list.length - 1;
                    // if (last > -1) {
                    //     const to = list[last].to;
                    //     if (to && to.indexOf(path) > -1) list[last].to = list[last].href = "";
                    // }
                    return list;
                };
            },
            /**
           * 获取所有全选标识符
           */
            getAuthList(state) {
                return Object.values(state.menuList).map(function (item) { return item.labelId })
            },
            /**
             * 获取当前匹配的路由数据
             */
            getMatchRoute() {
                return function (path, menuList) {
                    if (!path) return;
                    let routeData, length = 0;
                    menuList.forEach((item) => {
                        const { props, linklistId } = item;
                        if (!props || linklistId) return;
                        let to = props.to || '', len = to.length;
                        // indexOf有问题，如/home/account与/home/accountmanage会判断成一个路径 增加判断
                        if (to && path.indexOf(to) == 0 && path.replace(to)[0] === '/' && len > length) {
                            routeData = item;
                            length = len;
                        }
                    });
                    return routeData;
                }
            },
            getNoticeEevntTypes(state,) {
                return state.noticeEventTypes;
            },
        },
        mutations: {
            setNavTitleIds(state, payload = []) {
                state.navTitleIds = payload;
            },
            setRouteId(state, payload) {
                localStorage.setItem("ROUTEID", payload || '', { scope: '', version: '' });
                Cookies.set('ROUTEID', payload || '', { domain: global.DOMAIN, expires: 7 });
                state.routeId = payload;
            },
            setModuleList(state, payload = []) {
                let obj = {};
                payload.forEach(function (item) {
                    // console.log(item,'11111')
                    obj[item.id] = {
                        id: item.id,
                        title: item.title,
                        langKey: item.langKey,
                        iconClass: item.iconClass,
                    }
                });
                // console.log(obj,'obj')
                localStorage.setItem("MODULELIST", JSON.stringify(obj), { scope: '', version: '' });
                state.moduleList = obj;
            },
            setSysScopeList(state, payload = []) {
                let obj = {};
                payload.forEach(function (item) {
                    obj[item.id] = {
                        id: item.id,
                        url: handleHostname(envhelper.genEnvUrlByWebUrl(item.url, process.env.VUE_APP_HOST_PREFIX || 'production')),
                        title: item.title
                    }
                });
                localStorage.setItem("SYSSCOPELIST", JSON.stringify(obj), { scope: '', version: '' });
                state.sysScopeList = obj;
            },
            setNoticeEventTypes(state, payload = []) {
                const arr = payload.map(function (item) {
                    return {
                        id: item.id,
                        isSystem: item.isSystem,
                        label: item.label,
                        langKey: item.langKey,
                        title: item.title,
                    }
                });
                localStorage.NOTICEEVENTTYPES = JSON.stringify(arr);
                state.noticeEventTypes = arr;
            },
            setMenuList(state, payload = []) {
                const obj = {}, sysScopes = state.sysScopeList || {};
                payload.forEach(function (item, sortIndex) {
                    let {
                        title,
                        id,
                        url = '',
                        parentId,
                        menuType,
                        globalCatelogId: moduleId,
                        iconClass,
                        labelId,
                        scope,
                        langKey,
                        depth
                    } = item;
                    const isVue = scope == process.env.VUE_APP_PROJECT_ID,
                        hasProtocol = /^https?\:\/\//i.test(url),
                        props = hasProtocol ? { tag: "a", href: handleHostname(url) } : (
                            isVue ? { to: url } : { tag: "a", href: ((sysScopes[scope] || {}).url || '') + url }
                        ),
                        validate = menuType !== "NO";
                    // let iconType;
                    // if (/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/i.test(iconClass)) iconType = 'html';
                    // if (/^(https?:\/)?\/\w+/i.test(iconClass)){
                    //     iconType = 'html';
                    //     iconClass=`<img src=${iconClass} width='12px'/>`
                    // }
                    obj[id] = {
                        isVue,
                        title,
                        langKey,
                        id,
                        parentId,
                        icon: iconClass || "arrow-dropright",
                        // iconType,
                        props,
                        moduleId,
                        validate,
                        menuType,
                        sortIndex,
                        labelId,
                        depth
                    };
                });
                const objValues = Object.values(obj);
                objValues.forEach(function (item) {
                    const { id, parentId, validate, sortIndex } = item,
                        parent = obj[parentId];
                    if (parent && validate) {
                        // if(!parent.iconType) parent.icon = "folder";
                        parent.icon = "folder";
                        if (parent.linklistId) {
                            parent.linklistId[sortIndex] = id;
                        }
                        else {
                            parent.linklistId = { [sortIndex]: id };
                        }
                    }
                });
                objValues.forEach(function (item) {
                    if (item.linklistId) item.linklistId = Object.values(item.linklistId);
                })
                sessionStorage.MENULIST = JSON.stringify(obj);
                state.menuList = obj;
                // console.log(obj, 'menuList')
            },
        },
        actions: {
            async actionMenuList({ commit }, payload) {
                // 是否切换过用户
                let flag = false;
                // 是否需要在本窗口刷新
                let needRefresh = false;
                // 当前窗口的上一个用户Id
                let sessionUserId = sessionStorage.getItem('USERID');
                // 这个域名下上一个登录的用户Id
                let userId = Cookies.get('userId');
                // console.log('cookie中的userId', userId, 'sessionstorage中的userId', sessionUserId, '当前userId', this.state.userinfo.id);
                // 用户没有进行过登出的操作
                if (!userId) {
                    flag = false;
                }
                // 是否切换过用户
                else if (userId != this.state.userinfo.id) {
                    flag = true;
                }
                // 切换过用户后是否需要在本窗口刷新
                if (sessionUserId != this.state.userinfo.id) {
                    needRefresh = true;
                }
                // console.log('是否已经切换用户', flag, '是否需要在本窗口刷新', needRefresh);
                // 需要刷新
                if (needRefresh) {
                    localStorage.removeItem("MODULELIST");
                    localStorage.removeItem("SYSSCOPELIST");
                    localStorage.removeItem("NOTICEEVENTTYPES");
                    sessionStorage.removeItem("MENULIST");
                    // console.log('需要刷新');
                }

                if (userId) {
                    sessionStorage.setItem('USERID', this.state.userinfo.id);
                }
                // 原来的逻辑，其中有任何一项不存在的情况下，就会重新请求数据
                const moduleList = localStorage.MODULELIST,
                    sysScopeList = localStorage.SYSSCOPELIST,
                    menuList = sessionStorage.MENULIST,
                    noticeEventTypes = localStorage.NOTICEEVENTTYPES;
                if (menuList && moduleList && sysScopeList && noticeEventTypes && !payload) {
                    return;
                }
                // console.log('已刷新数据');
                const [moduleData, menuData] = await Promise.all([
                    HttpModuleList(),
                    HttpMenuList({ withNoVerify: 1 })
                ]).catch(err => {
                    localStorage.removeItem("MODULELIST");
                    localStorage.removeItem("SYSSCOPELIST");
                    localStorage.removeItem("NOTICEEVENTTYPES");
                    sessionStorage.removeItem("MENULIST");
                    return Promise.reject(err);
                });
                if (menuData && moduleData.data) {
                    commit("setModuleList", moduleData.data.globalcatelogs);
                    commit('setSysScopeList', moduleData.data.systems)
                    commit('setNoticeEventTypes', moduleData.data.bizeventtypes)
                    commit("setMenuList", menuData.data);
                }
            }
        }
    }
};